package com.java.study.boot;

import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author yuansheng.xu
 */
@SpringBootApplication
@EnableFeignClients
public class CloudConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(CloudConsumerApplication.class, args);
    }

    @LoadBalanced
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    @RestController
    public static class TestController {
        @Autowired
        RestTemplate restTemplate;

        @Value("${spring.application.name}")
        String applicationName;

        @Autowired
        FeignClientService feignClientService;

        @RequestMapping(value = "/hello/1", method = RequestMethod.GET)
        public String hello() {
            /*  这里通过服务名cloudServiceProvider调用其他服务的hello接口 */
            return restTemplate.getForObject("http://cloud-service-provider/hello/", String.class);
        }

        @RequestMapping(value = "/hello/feign", method = RequestMethod.GET)
        public String feign() {
            /*  这里通过feignClient调用服务cloudServiceProvider的hello接口 */
            return feignClientService.hello() + " feign";
        }

        @RequestMapping(value = "/echo", method = RequestMethod.GET)
        public String echo() {
            /*  这里通过服务名调用自己的echo2接口 */
            return restTemplate.getForObject("http://" + applicationName + "/echo2", String.class) + " from echo";
        }

        @RequestMapping(value = "/echo2", method = RequestMethod.GET)
        public String echo2() {
            return "consumer echo2  random:" + RandomStringUtils.randomAlphabetic(41);
        }
    }

}
